<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          流程备注:
          <NInput v-model:value="paginationReactive.remark" placeholder="请输入流程备注" clearable class="commonWidth">
          </NInput>
          流程类型:
          <NSelect :options="parentCodeList" placeholder="请选择流程类型" clearable style="width: 200rem" label-field="name"
            value-field="value" v-model:value="paginationReactive.functionCode" class="commonWidth" filterable
            :render-option="renderOption"  />
          申请日期:
          <NDatePicker input-readonly placeholder="请选择申请日期" v-model:formatted-value="range" clearable type="daterange"
            style="width: 300rem"></NDatePicker>
          申请人:
          <NInput v-model:value="paginationReactive.applicant" placeholder="请输入申请人" clearable class="commonWidth">
          </NInput>
          <NButton type="primary" style="width: 78rem" ghost @click="searchTable">
            查询
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="resetVisible" @close="resetVisible = false">
    <VDialogContent @close="resetVisible = false" @submit="resetReapproval" title="重新审批提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定重新审批吗？
      </div>
    </VDialogContent>
  </NModal>
</template>
<script setup lang="ts">
import { h, reactive, onMounted, ref, watch, type VNode, onDeactivated } from 'vue'
import {
  NSpace,
  NButton,
  NDataTable,
  NPagination,
  NSelect,
  useMessage,
  NInput,
  NDatePicker,
  NTooltip,
  NModal
} from 'naive-ui'
import type { DataTableColumns, SelectOption } from 'naive-ui'
import TableView from '@/components/TableView.vue'
import router from '@/router'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { UserModel } from '@/api/userCenter'
import { useRoute } from 'vue-router'
import { useViewerStore } from '@/views/OA/Common/store'
import { RecordType } from '@/router/utils'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'

const useStore = useViewerStore()
const message = useMessage()
const route = useRoute()

const columns: DataTableColumns = [
  {
    title: '部门',
    key: 'deptName',
    width: 70,
    align: useStore.isCenter
  },
  {
    title: '申请人',
    key: 'createBy',
    width: 40,
    align: useStore.isCenter
  },
  {
    title: '流程类型',
    key: 'codeName',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '流程备注',
    key: 'remark',
    width: 200,
    align: useStore.isCenter
  },
  {
    title: '申请时间',
    key: 'createTime',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '流程状态',
    key: 'fromStatusCode',
    width: 40,
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: useStore.isCenter,
    width: 60,
    fixed: 'right',
    render: (row: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeFalse(row.code)
            const path = jumpRouterList.value.find((it: any) => it.code == row.code)?.routeOne
            if (path) router.push({ path, query: { id: row.resourceId as never, redirect: router.currentRoute.value.fullPath } })
            else message.error('功能正在开发中')
          }
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: { display: row.code == 'A0518' && row.reapprovalButton ? 'inline-block' : 'none' },
          onClick: async () => {
            fromId.value = row.id
            resetVisible.value = true
          }
        },
        {
          default: () => '重新审批'
        }
      )
    ]
  }
]
// 上一页下一页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 50,
  functionCode: null, //类型
  remark: null, //备注
  applicant: null, //申请人
  startTime: null, //开始时间
  endTime: null, //结束时间
  onChange: (page: number) => {
    paginationReactive.page = page
    getDisposeList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getDisposeList()
  }
})
// 重新审批
const fromId = ref()
const resetVisible = ref(false)
const resetReapproval = async () => {
  const [error, res] = await sendRequest<HttpResponse<UserModel>>({
    module: 'userCenter',
    api: 'reapprovalButton',
    override: {
      params: {
        fromId: fromId.value
      }
    }
  })
  if (error) return message.error(error.message), resetVisible.value = false
  if (res.code !== 0) return message.error(res.msg), resetVisible.value = false
  resetVisible.value = false
  router.push({ path: '/OA/UserCenter/Examine' })
}
// select的Tooltip
const renderOption = ({ node, option }: { node: VNode; option: SelectOption }) => {
  return h(NTooltip, { style: { backgroundColor: '#e1e1e1' } }, {
    trigger: () => node,
    default: () => option.name
  })
}
//获取需要跳转的路由
const jumpRouterList: any = ref([])
const getJumpRouterList = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'userCenter',
    api: 'getJumpRoute'
  })
  if (error) return message.error(error.message)
  jumpRouterList.value = res.data
}
//流程类型
const parentCodeList: any = ref([])
const getFunction = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'progress',
    api: 'getWorkFlowFunctionCodeList',
  })
  if (error) return message.error(error.message)
  parentCodeList.value = res.data
}
// 获取列表
const tableData = ref([])
const tableLoading = ref(false)
const getDisposeList = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<UserModel>>({
    module: 'userCenter',
    api: 'disposeList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        functionCode: paginationReactive.functionCode,
        startTime: paginationReactive.startTime,
        applicant: paginationReactive.applicant,
        remark: paginationReactive.remark,
        endTime: paginationReactive.endTime
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = res.data.list
  paginationReactive.itemCount = res.data.totalCount
}
// 查询
const range: any = ref()
const searchTable = () => {
  paginationReactive.page = 1
  paginationReactive.startTime = range.value ? range.value[0] : null
  paginationReactive.endTime = range.value ? range.value[1] : null
  getDisposeList()
}

onMounted(() => {
  getJumpRouterList()
  getFunction()
})

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,getDisposeList())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  () => {
    if (route.path == '/OA/UserCenter/Dispose') {
      getDisposeList()
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>
<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}

.commonWidth {
  width: 150rem;
}
</style>
